package com.yantong.resolver;

import com.yantong.exception.BDException;
import com.yantong.result.ResultVo;
import com.yantong.pojo.Member;
import com.yantong.service.MemberService;
import com.yantong.annotation.Auth;
import com.yantong.annotation.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@ApiIgnore  @LoginUser注解的方法参数，注入当前登录用户
 *
 * @author Kyle
 * @email 572001183@qq.com
 * @date 2017-03-23 22:02
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private MemberService memberService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Member.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        Auth auth = parameter.getMethodAnnotation(Auth.class);

        String token = request.getHeader("Authorization");

        if ((token == null) || (token.isEmpty())) {
            token = request.getParameter("Authorization");
        }

        if ((token == null) || (token.isEmpty())) {
            return ResultVo.error("无接口访问权限");
        }

        if( "dehua".equals(token)){
            Integer mid = Integer.parseInt(request.getParameter("dehua"));
            Member member = memberService.getByKey(mid.longValue());
            return member;
        }

        Long mid = null;
        if(StringUtils.isNotEmpty(token)){
            String  obj  = redisTemplate.opsForValue().get(token);
            if(obj != null){
                mid = Long.parseLong(obj.toString());
            }
        }
        //查询的用户id
        Long userId = 0L;
        if(auth != null && auth.needPass()){
            if(mid != null){
                userId = mid;
            }
        }else{
            if (mid == null) {
                throw new BDException("token失效，请重新登录！", 401);
            }
            userId = mid;
        }

        //获取用户信息
        Member member = memberService.getByKey(userId);

        return member;
    }
}
